<template>
  <div class="user-admin-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="60px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="用户名">
              <el-input
                v-model="searchForm.username"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="行政编码">
              <el-input
                v-model="searchForm.parentCode"
                placeholder="请输入行政编码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增用户
      </el-button>
    </div>

    <!-- 表格 -->
    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%;display:flex;"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="userId" label="用户ID" width="100" align="center" />
        <el-table-column prop="username" label="用户名" width="180" show-overflow-tooltip />
        <el-table-column prop="parentCode" label="行政编码" width="180" show-overflow-tooltip />
        <el-table-column label="角色" width="180" align="center">
          <template #default="{ row }">
            <el-tag :type="row.roleId === 1 ? 'danger' : 'success'">
              {{ roleMap[row.roleId] || '未知角色' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="行政编码" prop="parentCode">
          <el-input v-model="formData.parentCode" placeholder="请输入行政编码" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="formData.roleId"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!formData.userId">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码（6 - 20位）"
            show-password
          />
        </el-form-item>
        <el-form-item label="密码" v-else>
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="留空表示不修改密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ElMessage } from 'element-plus';

export default {
  name: 'UserAdmin',
  data() {
    return {
      searchForm: {
        username: '',
        parentCode: ''
      },
      tableData: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增用户',
      formData: {
        userId: null,
        username: '',
        password: '',
        roleId: null,
        parentCode: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度2 - 20位', trigger: 'blur' }
        ],
        password: [
          { 
            required: (rule, value, callback) => {
              if (this.formData.userId) return callback() // 编辑时允许密码为空
              callback(value ? null : new Error('请输入密码'))
            }, 
            trigger: 'blur' 
          },
          { min: 6, max: 20, message: '密码长度6 - 20位', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        parentCode: [
          { required: true, message: '请输入行政编码', trigger: 'blur' },
          { pattern: /^\d+$/, message: '行政编码需为数字', trigger: 'blur' } // 可根据实际需求调整
        ]
      },
      roleOptions: [],
      roleMap: {},
      roleLoading: false
    }
  },
  created() {
    this.fetchData()
    this.fetchRoles()
  },
  methods: {
    fetchData() {
      this.loading = true
      request.get('/user/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          username: this.searchForm.username,
          parentCode: this.searchForm.parentCode
        }
      })
      .then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      })
      .catch(err => {
        console.error('获取用户列表失败:', err)
        this.$message.error('加载用户列表失败')
      })
      .finally(() => {
        this.loading = false
      })
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        username: '',
        parentCode: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.formData = {
        ...row,
        password: '' // 编辑时清空密码输入框（如需保留需调整）
      }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm(`确认删除用户 ${row.username} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post(`/user/delete/${row.userId}`)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
          .catch(err => {
            this.$message.error('删除失败')
          })
      }).catch(() => {})
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        const isEdit = !!this.formData.userId
        const apiUrl = isEdit ? '/user/update' : '/user/create'
        const submitData = {
          ...this.formData,
          // 编辑时若密码为空则不传递（避免覆盖原有密码）
          password: isEdit && this.formData.password === '' ? undefined : this.formData.password
        }

        request.post(apiUrl, submitData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || `${this.dialogTitle}失败`)
            }
          })
          .catch(err => {
            this.$message.error(`${this.dialogTitle}失败`)
          })
      })
    },
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.formData = {
        userId: null,
        username: '',
        password: '',
        roleId: null,
        parentCode: ''
      }
    },
    async fetchRoles() {
      this.roleLoading = true
      try {
        const res = await request.get('/role/list')
        if (res.code === 200) {
          this.roleOptions = res.data.records.map(item => ({
            value: item.roleId,
            label: item.roleName
          }))
          this.roleMap = res.data.records.reduce((acc, item) => {
            acc[item.roleId] = item.roleName
            return acc
          }, {})
        } else {
          ElMessage.error(res.message || '获取角色列表失败')
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        ElMessage.error('获取角色列表失败，请检查网络连接')
      } finally {
        this.roleLoading = false
      }
    }
  }
}
</script>

<style scoped>
.user-admin-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display:flex;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
}
</style>